package c.a.md.androidvideo.widget;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.io.InputStream;

/**
 * Created by ytf on 2018/10/15.
 * Description:
 */
public class SurfaceImageViewDisplay extends SurfaceView implements SurfaceHolder.Callback, Runnable
{

    SurfaceHolder mHolder;
    Bitmap bmp;


    private Canvas mCanvas;

    public SurfaceImageViewDisplay(Context context)
    {
        this(context, null);
    }

    public SurfaceImageViewDisplay(Context context, AttributeSet attrs)
    {
        this(context, attrs, 0);
    }

    public SurfaceImageViewDisplay(Context context, AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init()
    {
        mHolder = getHolder();
        mHolder.addCallback(this);
        setFocusable(true);
        setFocusableInTouchMode(true);
        setKeepScreenOn(true);

        try
        {
            AssetManager am = getResources().getAssets();
            InputStream is = am.open("lbxx.png");
            bmp = BitmapFactory.decodeStream(is);
        }catch (Exception e)
        {

        }
    }

    private boolean isRunning;

    @Override
    public void surfaceCreated(SurfaceHolder holder)
    {
        isRunning = true;
        new Thread(this).start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
    {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder)
    {
        isRunning = false;
    }

    @Override
    public void run()
    {
        while (isRunning)
        {
            SystemClock.sleep(100);
            draw();
        }
    }

    private void draw()
    {
        try
        {
            //锁定画布并返回画布对象
            mCanvas = mHolder.lockCanvas();
            mCanvas.drawBitmap(bmp, 0, 0, null);
        } catch (Exception e)
        {
        } finally
        {
            //当画布内容不为空时，才post，避免出现黑屏的情况。
            if (mCanvas != null)
                mHolder.unlockCanvasAndPost(mCanvas);
        }
    }

}